<template lang="pug">
  .page
    .search-form.mb-10.pl-10.pr-10
      Row(type="flex" justify="start")
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 客户名称：
          Input(v-model="name" placeholder="请输入" clearable)
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 客户所属：
          .choose-saler
            Tooltip(placement="bottom" max-width="200" :disabled="!tipIsShow" theme="light")
              Input.input(v-model="dolderNames" type="text" readonly clearable @on-clear="salersClear")
              div(slot="content")
                .font-14 {{dolderNames}}
            .button(@click="chooseSaler") 选择
          //- Input(v-model="salerName" placeholder="请输入" clearable)
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 企业性质：
          Select(v-model="character"  placeholder="请选择" clearable)
            Option(v-for="(item, index) in characterArr" :value="item.key" :key="index") {{ item.value }}
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 企业规模：
          Select(v-model="size"  placeholder="请选择" clearable)
            Option(v-for="(item, index) in sizeArr" :value="item.key" :key="index") {{ item.value }}
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 所属行业：
          Select(v-model="businessType"  placeholder="请选择" clearable)
            Option(v-for="(item, index) in customerBusinesstype_arr" :value="item.key" :key="index") {{ item.value }}
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 注册资本：
          Input.unit-input(v-model="registerCapital")
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 客户标签：
          Select(v-model="tagId"  placeholder="请选择" clearable)
            Option(v-for="(item, index) in arrListDown.SalesCustomerTag" :value="item.value" :key="index") {{ item.label }}
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 客户类型：
          Select(v-model="signedType"  placeholder="请选择" clearable)
            Option(v-for="(item, index) in customersignedtype" :value="item.key" :key="index") {{ item.value }}
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          Button(type="info" @click="searchBtn") 查询
    .pl-20.pr-20.bg-white
      Table.hasTitle-table.beautiful-table(width="100%" :loading="loading" stripe :columns="setThead" :data="listData" @on-selection-change="tableSelectChange")
        div(slot="header")
          .pull-left.table-title-lefttxt
            span.leftText
              | 我的客户数:
              span.text-info.pl-5.pr-5.font-weight {{codeTotal}}
          .pull-right.table-title-btns
            Button.mr-15(v-if="hasHRDC_ImportPrivateCustomers" type="info" @click="importBtn") 客户导入
            Button.mr-15(v-if="hasHRDC_ExportPrivateCustomers" type="info" @click="exportBtn") 客户导出
            Button.mr-15(type="info" @click="downloadShizi") 十字询问法下载
            //- Button.mr-15(type="warning" size="small" @click="") 批量抛出
        template(slot-scope="{ row, index }" slot="updateSign")
          i-switch(v-model="row.signType" :true-value="1" :false-value="0" true-color="#19be6b" @on-change="updateSignChange(row.id, row.signType)")
            span(slot="open") 是
            span(slot="close") 否
        template(slot-scope="{ row, index }" slot="name")
          .u-d-info(@click="gotoDetail(row.id)") {{row.name}}
        template(slot-scope="{ row, index }" slot="contact")
          Button(size="small" @click="gotoContact(row.id)") 查看
        template(slot-scope="{ row, index }" slot="communicate")
          Button.mr-5(type="info" size="small" @click="addCommunication(row.id)") 添加
          Button.mr-5(type="info" size="small" @click="checkCommunication(row.id)") 查看
        template(slot-scope="{ row, index }" slot="action")
          Button.mr-5(v-if="hasHRDC_PostBudget" type="text" size="small" @click="createBtn(row.id)") 添加预算
          Button.mr-5(v-if="hasHRDC_SetPublic" type="text" size="small" @click="setPublic(row.id)") 抛出
          Button.mr-5(v-if="hasHRDC_SetCustomerTag" type="text" size="small" @click="handleShowCustomerTagModal(row)") 标记客户标签
        .clearfix.pl-20.pr-20(slot="footer")
          Page(:total="codeTotal" :current="PageIndex" :page-size="PageSize" prev-text="上一页" next-text="下一页" @on-change="pageChangeFn" show-total @on-page-size-change="onpageSizeChange" show-sizer :page-size-opts="[10, 20, 30, 50, 100]")
      //- div(style="margin: 10px;overflow: hidden")
      //-   div(style="float: right;")
      //-     Page(:total="codeTotal" :current="PageIndex" :page-size="PageSize" prev-text="上一页" next-text="下一页" @on-change="pageChangeFn" show-total @on-page-size-change="onpageSizeChange" show-sizer :page-size-opts="[10, 20, 30, 50, 100]")
    Modal(v-model="createModal" title="客户预算" width="800")
      Form(ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="110")
        FormItem(label="今年计划：" prop="plan")
          Input(v-model="formValidate.plan" type="textarea" placeholder="请输入")
        FormItem(label="今年预算：" prop="budgetDetail")
          Input(v-model="formValidate.budgetDetail" type="textarea" placeholder="请输入")
        FormItem(label="过往供应商：" prop="historySuppliers")
          Input(v-model="formValidate.historySuppliers" type="textarea" placeholder="请输入")
        FormItem(label="过往项目：" prop="historyProjects")
          Input(v-model="formValidate.historyProjects" type="textarea" placeholder="请输入")
      template(slot="footer")
        Button(type="info" @click="handleSubmit('formValidate')") 提交
        Button(@click="createModal = false") 取消
    createCommunication(ref="createCommunication" :customerId="customerId" :contact_arr="contact_arr" :communicationtype="communicationtype")
    checkCommunication(ref="checkCommunication" :customerId="customerId" :communicationList="communicationList" :communicationTotal="communicationTotal" @get-list="getCommunicationList")
    importModal(ref="importModal" @get-list="getList")
    visibvleTreeList(ref="treeModal" :treeData="treeData" @on-change="getSalerId")
    CustomerTagModal(ref="CustomerTagModal" @query="getList")
</template>

<script>
import HRDCCustomerApi from '@/api/HRDCCustomer.api.js'
import Mixin from '../coustomerMixin.js'
import createCommunication from '../../HRDC-common/communication/create.vue'
import checkCommunication from '../../HRDC-common/communication/check.vue'
import importModal from './modal/import.vue'
import CustomerTagModal from './modal/customerTag.vue'
import { Common } from '@/utils/common.js'
export default {
  name: 'h-c-private',
  data () {
    return {
      createModal: false,
      name: '',
      salerName: '',
      updateSign: 1,
      character: '', // 企业性质
      size: '', // 企业规模
      businessType: '', // 所属行业
      registerCapital: '', // 注册资本
      tagId: '', // 客户标签
      signedType: '', // 客户类型
      thead: ['selection', 'signedTypeName', 'tagName', 'name', 'contact', 'characterName', 'businessTypeName', 'registerCapital', 'size', 'address', 'webSite', 'phone', 'holders', 'createrName', 'createTime', 'communicate', 'action'],
      listData: [],
      ids: [],
      loading: false,
      codeTotal: 0,
      PageIndex: 1,
      PageSize: 10,
      formValidate: {
        plan: '',
        budgetDetail: '',
        historySuppliers: '',
        historyProjects: ''
      },
      ruleValidate: {
        plan: [
          { required: true, message: '今年计划不能为空', trigger: 'blur' }
        ],
        budgetDetail: [
          { required: true, message: '今年预算不能为空', trigger: 'blur' }
        ],
        historySuppliers: [
          { required: true, message: '过往供应商不能为空', trigger: 'blur' }
        ],
        historyProjects: [
          { required: true, message: '过往供应商不能为空', trigger: 'blur' }
        ]
      },
      arrListDown: {
        SalesCustomerTag: [],
      },
      customersignedtype: []
    }
  },
  mixins: [Mixin],
  components: {
    createCommunication,
    checkCommunication,
    importModal,
    CustomerTagModal
  },
  computed: {
    setThead () {
      return this.getTableColumns(this.thead)
    },
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    hasImport () {
      return this.actionArr.indexOf('HRDC_ImportPrivateCustomers') > -1
    },
    hasExport () {
      return this.actionArr.indexOf('HRDC_ExportPrivateCustomers') > -1
    },
    // 添加预算
    hasHRDC_PostBudget () {
      return this.actionArr.indexOf('HRDC_PostBudget') > -1
    },
    // 抛出
    hasHRDC_SetPublic () {
      return this.actionArr.indexOf('HRDC_SetPublic') > -1
    },
    // 客户导入
    hasHRDC_ImportPrivateCustomers () {
      return this.actionArr.indexOf('HRDC_ImportPrivateCustomers') > -1
    },
    // 标记客户标签
    hasHRDC_SetCustomerTag () {
      return this.actionArr.indexOf('HRDC_SetCustomerTag') > -1
    },
    // 标记KA重点客户
    hasHRDC_SetKACustomer () {
      return this.actionArr.indexOf('HRDC_SetKACustomer') > -1
    },
    // 客户导出
    hasHRDC_ExportPrivateCustomers () {
      return this.actionArr.indexOf('HRDC_ExportPrivateCustomers') > -1
    },
    // 查询
    hasHRDC_GetPrivateCustomers () {
      return this.actionArr.indexOf('HRDC_GetPrivateCustomers') > -1
    },
    // 标记普通客户
    hasHRDC_SetCommonCustomer () {
      return this.actionArr.indexOf('HRDC_SetCommonCustomer') > -1
    }
  },
  created () {
    this.salesCustomerTag()
    this.getList()
  },
  watch: {
    $route (to, from) {
      if (to.name === 'h-c-private') {
        this.getList()
      }
    }
  },
  methods: {
    // 获取客户标签
    salesCustomerTag () {
      let typeName = 'SalesCustomerTag'
      Common.getSelectIdList(typeName, this.arrListDown)
    },
    // 获取客户列表
    getList () {
      this.loading = true
      HRDCCustomerApi.GetPrivateCustomers({
        name: this.name,
        salerName: this.salerName,
        HolderIds: this.salesIds,
        Character: this.character,
        Size: this.size,
        BusinessType: this.businessType,
        RegisterCapital: this.registerCapital,
        PageIndex: this.PageIndex,
        PageSize: this.PageSize,
        SignedType: this.signedType,
        TagId: this.tagId
      }).then(res => {
        this.loading = false
        if (res.data.success) {
          this.listData = res.data.data
          this.codeTotal = res.data.totalRows
        } else {
          
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    // 查看客户联系人信息
    gotoContact (id) {
      this.$router.push({ name: 'h-c-detail', query: { id: id, isCreate: true } })
    },
    // 抛出
    setPublic (id) {
      HRDCCustomerApi.SetPublic({
        id: id
      }).then(res => {
        if (res.data.success) {
          this.$Message.success(res.data.message)
          this.getList()
        } else {
          
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    // KA客户的编辑、删除
    updateSignChange (id, type) {
      console.log(id,type)
      HRDCCustomerApi.BatchUpdateSignType({
        Ids: [id],
        SignType: type
      }).then(res => {
        if (res.data.success) {
          this.$Message.success(res.data.message)
        } else {
          this.$Message.error(res.data.message)
        }
        this.getList()
      })
    },
    // 添加预算弹窗
    createBtn (id) {
      this.customerId = id
      this.createModal = true
      this.formValidate= {
        plan: '',
        budgetDetail: '',
        historySuppliers: '',
        historyProjects: ''
      }
    },
    // 添加预算
    postBudget () {
      HRDCCustomerApi.PostBudget(Object.assign({ CustomerId: this.customerId }, this.formValidate)).then(res => {
        if (res.data.success) {
          this.$Message.success(res.data.message)
          this.createModal = false
        } else {
          
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    // 提交预算按钮
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.postBudget()
        } else {
          this.$Message.warning('有必填项未填!')
        }
      })
    },
    // 查询
    searchBtn () {
      this.PageIndex = 1
      this.getList()
    },
    // 客户导入
    importBtn () {
      this.$refs.importModal.show()
    },
    // 客户导出
    exportBtn () {
      HRDCCustomerApi.ExportPrivateCustomers({
        selectedIds: this.ids,
        name: this.name,
        salerName: this.salerName,
        HolderIds: this.salesIds,
        Character: this.character,
        Size: this.size,
        BusinessType: this.businessType,
        RegisterCapital: this.registerCapital
      }).then(res => {
        if (res.data.success) {
          let objectUrl = res.data.data
          console.log(objectUrl)
          const link = document.createElement('a')
          link.download = ''
          link.href = objectUrl
          link.click()
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    downloadShizi () {
      const link = document.createElement('a')
      link.download = ''
      link.href = '/content/template/%E5%8D%81%E5%AD%97%E8%AF%A2%E9%97%AE%E6%B3%95.xlsx'
      link.click()
    },
    tableSelectChange (val) {
      console.log(val)
      this.ids = val.map(item => {
        return item.id
      })
      console.log(this.ids)
    },
    pageChangeFn (val) {
      this.PageIndex = val
      this.getList()
    },
    onpageSizeChange (val) {
      this.PageSize = val
      this.getList()
    },

    // 标记客户标签-打开弹窗
    handleShowCustomerTagModal (row) {
      this.$refs.CustomerTagModal.show(row)
      this.$refs.CustomerTagModal.arrListDown = this.arrListDown
    },
  }
}
</script>

<style>

</style>
